package org.glut.backend.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.backend.domain.Orders;
import org.glut.backend.domain.StreetFood;
import org.glut.backend.domain.StreetFoodOrders;
import org.glut.backend.dto.MovieOrderDTO;
import org.glut.backend.dto.StreetFoodOrderDTO;
import org.glut.backend.mapper.OrdersMapper;
import org.glut.backend.mapper.StreetFoodMapper;
import org.glut.backend.mapper.StreetFoodOrdersMapper;
import org.glut.backend.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.glut.backend.util.RedisUtil;
import org.glut.backend.vo.OrderListVO;
import org.glut.backend.vo.StreetOrdersItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author xiuci1412
 * @since 2025-08-07 14:26
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {


    @Value("${alipay.notifyUrl}")
    public String notifyUrl;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private RedisUtil redisUtil;

    private static final String ORDER_COUNTDOWN_PREFIX = "order:countdown:";

    @Autowired
    private StreetFoodOrdersMapper streetFoodOrdersMapper;

    @Autowired
    private StreetFoodMapper streetFoodMapper;


    @Override
    public IPage<OrderListVO> getList(Integer userId,Integer pageNo, Integer pageSize) {
        Page<OrderListVO> orderListVOPage = new Page<>(pageNo, pageSize);
        //先写死
        IPage<OrderListVO> list = baseMapper.getList(orderListVOPage, userId);
        list.getRecords().forEach(orderListVO -> {
            List<StreetFoodOrders> streetFoodOrderList = streetFoodOrdersMapper.selectList(new QueryWrapper<StreetFoodOrders>().eq("order_no", orderListVO.getOrderNo()));
            List<StreetOrdersItemVO> streetOrdersItems = streetFoodOrderList.stream().map(item -> {
                StreetOrdersItemVO streetOrdersItemVO = new StreetOrdersItemVO();
                streetOrdersItemVO.setNum(item.getNum());
                streetOrdersItemVO.setPrice(item.getPrice());
                StreetFood streetFood = streetFoodMapper.selectById(item.getStreetFoodId());
                streetOrdersItemVO.setStreetFoodName(streetFood.getName());
                return streetOrdersItemVO;
            }).collect(Collectors.toList());
            orderListVO.setStreetFoods(streetOrdersItems);
        }); return list;
    }

    @Override
    public ResponseEntity alipay(MovieOrderDTO movieOrderDTO, HttpServletRequest request, HttpServletResponse response) {
        String orderNo = null;
        String total_amount = null;

        if (StringUtils.isEmpty(movieOrderDTO.getOrderNo())) {
            orderNo = UUID.randomUUID().toString().replaceAll("-", "");
            total_amount = movieOrderDTO.getTotalAmount().toString();
            Orders orders = new Orders();
            orders.setOrderNo(orderNo);
            orders.setStatus(0);
            orders.setCreateTime(LocalDateTime.now());
            orders.setUserId(movieOrderDTO.getUserId());
            orders.setTotalPrice(new BigDecimal(total_amount));
            orders.setSchedulingId(movieOrderDTO.getSchedulingId());
            orders.setSoldSeat(movieOrderDTO.getSoldSeats());
            baseMapper.insert(orders);
            for (StreetFoodOrderDTO streetFoodOrderDTO : movieOrderDTO.getStreetFoodOrderList()) {
                StreetFoodOrders streetFoodOrders = new StreetFoodOrders();
                streetFoodOrders.setOrderNo(orderNo);
                streetFoodOrders.setStreetFoodId(streetFoodOrderDTO.getStreatFoodId());
                streetFoodOrders.setNum(streetFoodOrderDTO.getNum());
                streetFoodOrders.setPrice(streetFoodOrderDTO.getPrice());
                streetFoodOrdersMapper.insert(streetFoodOrders);
            }
            // 将订单ID存入Redis，设置10分钟（600秒）过期时间
            String redisKey = ORDER_COUNTDOWN_PREFIX + orders.getId();
            redisUtil.set(redisKey, orders.getId().toString(), 600);
        } else {
            orderNo = movieOrderDTO.getOrderNo();
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getOrderNo, orderNo);
            Orders orders = baseMapper.selectOne(ordersLambdaQueryWrapper);
            orderNo = orders.getOrderNo();
            total_amount = orders.getTotalPrice().toString();
        }


        AlipayTradePrecreateRequest alipayTradePrecreateRequest = new AlipayTradePrecreateRequest(); //创建API对应的request类
        alipayTradePrecreateRequest.setNotifyUrl(notifyUrl);
        alipayTradePrecreateRequest.setBizContent("{" + "\"out_trade_no\":\"" + orderNo + "\"," + // 商户订单号
                "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + "电影票订单" + "\"," + "\"store_id\":\"" + "猫眼" + "\"}");
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = null;
        try {
            alipayTradePrecreateResponse = alipayClient.execute(alipayTradePrecreateRequest);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
            
        }
        if (alipayTradePrecreateResponse.isSuccess()) {
            log.info("支付API调用成功");
            Map map = new HashMap();
            map.put("orderNo", orderNo);
            map.put("qrCode", alipayTradePrecreateResponse.getQrCode());
            return ResponseEntity.ok(map);
        } else {
            log.info("支付API调用失败");
        }
        return ResponseEntity.ok(false);
    }

    @Override
    public void nofity(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

        if (trade_status.equals("TRADE_SUCCESS")) {
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getOrderNo, out_trade_no);
            Orders orders = baseMapper.selectOne(ordersLambdaQueryWrapper);
            if (orders != null) {
                orders.setStatus(1);
                orders.setPayTime(LocalDateTime.now());
                baseMapper.updateById(orders);

                // 支付成功后删除Redis中的倒计时记录
                String redisKey = ORDER_COUNTDOWN_PREFIX + orders.getId();
                redisUtil.del(redisKey);
                log.info("订单{}支付成功，已删除Redis倒计时记录", orders.getId());
            }

        }
    }

    @Override
    public boolean deleteById(Integer id) {
        // 删除Redis中的倒计时记录
        String redisKey = ORDER_COUNTDOWN_PREFIX + id;
        redisUtil.del(redisKey);
        return baseMapper.deleteById(id) > 0;
    }
}